package com.example.stringbufferlogger.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.stringbufferlogger.entity.LogRecord;
import com.example.stringbufferlogger.mapper.LogReceiverMapper;
import com.example.stringbufferlogger.dto.LogEntryDTO;
import com.example.stringbufferlogger.service.LogReceiverService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class LogReceiverServiceImpl extends ServiceImpl<LogReceiverMapper, LogRecord> implements LogReceiverService {
    @Resource
    private LogReceiverMapper logReceiverMapper;

    @Override
    public int LogRecord(LogEntryDTO logEntryDTO) {
        LogRecord logRecord = new LogRecord();
        logRecord.setRequestId(logEntryDTO.getRequestId());
        logRecord.setMethod(logEntryDTO.getMethod());
        logRecord.setUrl(logEntryDTO.getUrl());
        logRecord.setSessionId(logEntryDTO.getSessionId());
        logRecord.setSessionAttributes(convertPretty(logEntryDTO.getSessionAttributes()));
        logRecord.setPath(logEntryDTO.getPath());
        logRecord.setRemoteIp(logEntryDTO.getRemoteIp());
        logRecord.setDuration(logEntryDTO.getDuration());
        logRecord.setHeaders(convertPretty(logEntryDTO.getHeaders()));
        logRecord.setRequestParams(convertPretty(logEntryDTO.getRequestParams()));
        logRecord.setRequestBody(logEntryDTO.getRequestBody());
        logRecord.setResponseBody(logEntryDTO.getResponseBody());
        logRecord.setStatus(logEntryDTO.getStatus());
        logRecord.setContentType(logEntryDTO.getContentType());
        logRecord.setReplayStatus(logEntryDTO.getReplayStatus());

        return logReceiverMapper.insert(logRecord);
    }

    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 美化输出
    public static String convertPretty(Map<?, ?> map) {
        try {
            return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Map转格式化JSON失败", e);
        }
    }
}
